/*
 * @author zei, QQ:77132995, email:kazeik@163.com
 * 2022/3/7 17:15
 * 类说明:
 */

import 'dart:convert';
import 'dart:io';

import 'package:base_plugin/base_plugin.dart';
import 'package:file_picker/file_picker.dart';
import 'package:finance_app/src/entities/data_import_entity.dart';
import 'package:finance_app/src/utils/file_utils.dart';
import 'package:flutter/material.dart';
import 'package:dio/dio.dart';
import 'package:path/path.dart' as path;

class DataImportProvider extends BaseProvider {
  List<DataImportEntity> _importItems;
  String _uploadFileName;

  List<DataImportEntity> get importItems => _importItems;

  set uploadFileName(String value) {
    _uploadFileName = value;
    update();
  }

  String get uploadFileName => _uploadFileName;

  set importItems(List<DataImportEntity> value) {
    _importItems = value;
    update();
  }

  @override
  Future get dataFuture => null;

  void downloadTemplateFile() async {
    obtainContext?.call((context) async {
      BaseConfig.dialogBase.showLoadingDialog(context: context, text: 'loading...');
      File file = await FileUtils.getExcelTemplate();
      await FileUtils.downloadExcelTemplate(file.path, onReceiveProgress: (progress, count) {
        if (progress == count) {
          Navigator.pop(context);
        }
      });
    });
  }

  void uploadTemplateFile() async {
    FilePickerResult result = await FilePicker.platform.pickFiles(
      type: FileType.custom,
      allowedExtensions: ['xls', 'xlsx'],
    );
    if (result != null) {
      File file = File(result.files.single.path);
      obtainContext?.call((context) async {
        BaseConfig.dialogBase.showLoadingDialog(context: context, text: 'loading...');
        await post(
            _uploadExcelFile(file.path, onSendProgress: (progress, count) {
              if (progress == count) {
                Navigator.pop(context);
              }
            }), onSuccess: (result) {
          _importItems = getEntityFromResult<List<DataImportEntity>>(result);
          uploadFileName = file.path.substring(file.path.lastIndexOf("/") + 1, file.path.length);
        });
      });
    }
  }

  Future<Response> _uploadExcelFile(String filePath, {ProgressCallback onSendProgress, bool import = false}) async {
    final file = await BaseConfig.httpBase.formFile(filePath, path.basename(filePath));

    return BaseConfig.httpBase.postForm('/api/contacts/excel', {'file': file, "is_import": import}, onSendProgress: onSendProgress);
  }

  void deleteSelectFile() {
    _importItems.clear();
    _importItems = null;
    uploadFileName = "";
  }
}
